package com.jinbooks.web.merchant.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jinbooks.authn.annotation.CurrentUser;
import com.jinbooks.entity.Message;
import com.jinbooks.entity.merchant.Merchant;
import com.jinbooks.entity.merchant.dto.MerchantPageDto;
import com.jinbooks.entity.merchant.vo.MerchantVo;
import com.jinbooks.entity.dto.ListIdsDto;
import com.jinbooks.entity.idm.UserInfo;
import com.jinbooks.persistence.service.MerchantService;
import com.jinbooks.validate.AddGroup;
import com.jinbooks.validate.EditGroup;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商户控制器
 *
 * @author lingma
 */
@RestController
@RequestMapping("/merchant")
@RequiredArgsConstructor
@Slf4j
public class MerchantController {
    private final MerchantService baseService;

    /**
     * 分页查询商户列表
     */
    @GetMapping("/fetch")
    public Message<Page<MerchantVo>> fetch(@ParameterObject MerchantPageDto dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("fetch {}", dto);
        return Message.ok(baseService.pageList(dto));
    }

    /**
     * 查询商户树列表
     */
    @GetMapping("/tree")
    public Message<List<MerchantVo>> tree(@CurrentUser UserInfo currentUser) {
        log.debug("tree {}", currentUser.getWorkspaceId());
        return Message.ok(baseService.treeList(currentUser.getWorkspaceId()));
    }

    /**
     * 获取商户详情
     */
    @GetMapping("/get/{id}")
    public Message<MerchantVo> get(@PathVariable("id") String id, @CurrentUser UserInfo currentUser) {
        log.debug("get {}", id);
        return new Message<>(Message.SUCCESS, baseService.getById(id, currentUser.getWorkspaceId()));
    }

    /**
     * 新增商户
     */
    @PostMapping("/save")
    public Message<Boolean> save(@Validated(AddGroup.class) @RequestBody Merchant dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("save {}", dto);
        return Message.ok(baseService.save(dto));
    }

    /**
     * 更新商户
     */
    @PutMapping("/update")
    public Message<Boolean> update(@Validated(EditGroup.class) @RequestBody Merchant dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("update {}", dto);
        return Message.ok(baseService.update(dto));
    }

    /**
     * 删除商户
     */
    @DeleteMapping("/delete")
    public Message<Boolean> delete(@Validated @RequestBody ListIdsDto dto, @CurrentUser UserInfo currentUser) {
        dto.setWorkspaceId(currentUser.getWorkspaceId());
        log.debug("delete {}", dto);
        return Message.ok(baseService.deleteByIds(dto.getListIds()));
    }
}